package com.ww.aiinterviewer.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.ww.aiinterviewer.annotation.AuthCheck;
import com.ww.aiinterviewer.common.BaseResponse;
import com.ww.aiinterviewer.common.DeleteRequest;
import com.ww.aiinterviewer.common.ErrorCode;
import com.ww.aiinterviewer.common.ResultUtils;
import com.ww.aiinterviewer.constant.UserConstant;
import com.ww.aiinterviewer.exception.BusinessException;
import com.ww.aiinterviewer.exception.ThrowUtils;
import com.ww.aiinterviewer.model.dto.chatroom.ChatRoomAddRequest;
import com.ww.aiinterviewer.model.dto.chatroom.ChatRoomEditRequest;
import com.ww.aiinterviewer.model.dto.chatroom.ChatRoomQueryRequest;
import com.ww.aiinterviewer.model.dto.chatroom.ChatRoomUpdateRequest;
import com.ww.aiinterviewer.model.entity.ChatRoom;
import com.ww.aiinterviewer.model.entity.User;
import com.ww.aiinterviewer.model.vo.ChatRoomVO;
import com.ww.aiinterviewer.service.ChatRoomService;
import com.ww.aiinterviewer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 聊天房间接口
 *
 * @author wangwang
 */
@RestController
@RequestMapping("/chat_room")
@Slf4j
public class ChatRoomController {

    @Resource
    private ChatRoomService chatRoomService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
//     * @param chatRoomAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChatRoom(HttpServletRequest request) {
//        if (chatRoomAddRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
        ChatRoom chatRoom = new ChatRoom();
        chatRoom.setTitle("默认面试房间");
//        BeanUtils.copyProperties(chatRoomAddRequest, chatRoom);
//        List<ChatMessage> messages = chatRoomAddRequest.getMessages();
//        if (messages != null) {
//            chatRoom.setMessages(JSONUtil.toJsonStr(messages));
//        }
        chatRoomService.validChatRoom(chatRoom, true);
        User loginUser = userService.getLoginUser(request);
        chatRoom.setUserId(loginUser.getId());
        boolean result = chatRoomService.save(chatRoom);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChatRoomId = chatRoom.getId();
        return ResultUtils.success(newChatRoomId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChatRoom(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        ChatRoom oldChatRoom = chatRoomService.getById(id);
        ThrowUtils.throwIf(oldChatRoom == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChatRoom.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chatRoomService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chatRoomUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChatRoom(@RequestBody ChatRoomUpdateRequest chatRoomUpdateRequest) {
        if (chatRoomUpdateRequest == null || chatRoomUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ChatRoom chatRoom = new ChatRoom();
        BeanUtils.copyProperties(chatRoomUpdateRequest, chatRoom);
        List<ChatMessage> messages = chatRoomUpdateRequest.getMessages();
        if (messages != null) {
            chatRoom.setMessages(JSONUtil.toJsonStr(messages));
        }
        // 参数校验
        chatRoomService.validChatRoom(chatRoom, false);
        long id = chatRoomUpdateRequest.getId();
        // 判断是否存在
        ChatRoom oldChatRoom = chatRoomService.getById(id);
        ThrowUtils.throwIf(oldChatRoom == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chatRoomService.updateById(chatRoom);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ChatRoomVO> getChatRoomVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ChatRoom chatRoom = chatRoomService.getById(id);
        if (chatRoom == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chatRoomService.getChatRoomVO(chatRoom));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chatRoomRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ChatRoom>> listChatRoomByPage(@RequestBody ChatRoomQueryRequest chatRoomRequest) {
        long current = chatRoomRequest.getCurrent();
        long size = chatRoomRequest.getPageSize();
        Page<ChatRoom> chatRoomPage = chatRoomService.page(new Page<>(current, size),
                chatRoomService.getQueryWrapper(chatRoomRequest));
        return ResultUtils.success(chatRoomPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chatRoomRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ChatRoomVO>> listChatRoomVOByPage(@RequestBody ChatRoomQueryRequest chatRoomRequest,
            HttpServletRequest request) {
        long current = chatRoomRequest.getCurrent();
        long size = chatRoomRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ChatRoom> chatRoomPage = chatRoomService.page(new Page<>(current, size),
                chatRoomService.getQueryWrapper(chatRoomRequest));
        return ResultUtils.success(chatRoomService.getChatRoomVOPage(chatRoomPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chatRoomRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ChatRoomVO>> listMyChatRoomVOByPage(@RequestBody ChatRoomQueryRequest chatRoomRequest,
            HttpServletRequest request) {
        if (chatRoomRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chatRoomRequest.setUserId(loginUser.getId());
        long current = chatRoomRequest.getCurrent();
        long size = chatRoomRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ChatRoom> chatRoomPage = chatRoomService.page(new Page<>(current, size),
                chatRoomService.getQueryWrapper(chatRoomRequest));
        return ResultUtils.success(chatRoomService.getChatRoomVOPage(chatRoomPage, request));
    }

    // endregion
    

    /**
     * 编辑（用户）
     *
     * @param chatRoomRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChatRoom(@RequestBody ChatRoomEditRequest chatRoomRequest, HttpServletRequest request) {
        if (chatRoomRequest == null || chatRoomRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ChatRoom chatRoom = new ChatRoom();
        BeanUtils.copyProperties(chatRoomRequest, chatRoom);
        List<ChatMessage> messages = chatRoomRequest.getMessages();
        if (messages != null) {
            chatRoom.setMessages(JSONUtil.toJsonStr(messages));
        }
        // 参数校验
        chatRoomService.validChatRoom(chatRoom, false);
        User loginUser = userService.getLoginUser(request);
        long id = chatRoomRequest.getId();
        // 判断是否存在
        ChatRoom oldChatRoom = chatRoomService.getById(id);
        ThrowUtils.throwIf(oldChatRoom == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChatRoom.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chatRoomService.updateById(chatRoom);
        return ResultUtils.success(result);
    }

}
